package edu.utn.tacs.grupouno.ui.server;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import edu.utn.tacs.grupouno.negocio.Analisis;
import edu.utn.tacs.grupouno.rest.api.AnalisisService;
import edu.utn.tacs.grupouno.rest.api.PacientesService;
import edu.utn.tacs.grupouno.ui.client.AnalisisUIService;
import edu.utn.tacs.grupouno.ui.client.dto.AnalisisDTO;
import edu.utn.tacs.grupouno.ui.client.dto.AnalisisDetalleDTO;
import edu.utn.tacs.grupouno.ui.server.factories.AnalisisDTOFactory;
import edu.utn.tacs.grupouno.ui.server.factories.AnalisisDetalleDTOFactory;

public class AnalisisUIServiceImpl extends RemoteServiceServlet implements AnalisisUIService {

	private static final long serialVersionUID = 397210699976284248L;
	private ClassPathXmlApplicationContext context;
	
	@Override
	public List<AnalisisDTO> getAnalisisFromPaciente(String pacienteId) {
		List<AnalisisDTO> retval = new ArrayList<AnalisisDTO>();
		try {
			if(context == null) {
				context = new ClassPathXmlApplicationContext("beans-ui.xml");
			}
			PacientesService proxy = context.getBean("pacientesService", PacientesService.class);
			List<Analisis> analisis = proxy.getAnalisis(pacienteId);
			AnalisisDTOFactory factory = new AnalisisDTOFactory();
			
			for(Analisis analis : analisis) {
				retval.add(factory.create(analis));
			}
			
			return retval;
		} catch(Exception e) {
			e.printStackTrace();
			return retval;
		}
	}

	@Override
	public AnalisisDetalleDTO getDetalledAnalisis(String id) {
		try {
			if(context == null) {
				context = new ClassPathXmlApplicationContext("beans-ui.xml");
			}
			AnalisisService proxy = context.getBean("analisisService", AnalisisService.class);
			Analisis analisis = proxy.getAnalisis(id);
			AnalisisDetalleDTOFactory factory = new AnalisisDetalleDTOFactory();
			AnalisisDetalleDTO dto = factory.create(analisis);
			return dto;
		} catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
